import Vue from 'vue'
import Vuex from 'vuex'
import persistedState from 'vuex-persistedstate'
import storeDefault from './default'

Vue.use(Vuex)

function getStoreDefault (name) {
  const def = storeDefault()
  let value = sessionStorage.getItem(name)
  // 判断是否是对象 或 数组
  try {
    value = JSON.parse(value)
    if (value === '{}' || value === '[]' || !value) {
      value = def[name]
    }
  } catch (e) {
    if (!value) {
      value = def[name]
    }
  }
  return value
}

const store = new Vuex.Store({
  state: {
    storeDictionary: getStoreDefault('storeDictionary'),
    storeRule: getStoreDefault('storeRule'),
    storeMainpage: getStoreDefault('storeMainpage'),
    storeMch: getStoreDefault('storeMch'),
    storeCashLink: getStoreDefault('storeCashLink'),
    // 客户端消息记录
    storeClientLog: getStoreDefault('storeClientLog'),
    storeClientStatus: getStoreDefault('storeClientStatus'),
    // 原storage
    storeStorage: getStoreDefault('storeStorage'),
    storeReport: getStoreDefault('storeReport'),
    // 病例类型
    settleTypeList: []
  },
  getters: {},
  actions: {},
  mutations: {
    SET_RULE (state, data = {}) {
      state.storeRule = data
    },
    SET_DICTIONARY (state, data = {}) {
      state.storeDictionary = data
    },
    SET_MAINPAGE (state, data = {}) {
      state.storeMainpage = data
    },
    SET_MCH (state, data = {}) {
      state.storeMch = data
    },
    SET_CASHLINK (state, data = {}) { // 结余分析
      state.storeCashLink = data
    },
    SET_CLIENT_STATUS (state, data = '') {
      state.storeClientStatus = data
    },
    SET_CLIENT_LOG (state, data = {}) {
      state.storeClientLog = data
    },
    // 用户管理
    SET_STORAGE (state, data) {
      state.storeStorage[data.key] = data.val
    },
    // 病例类型
    SET_SETTLETYPE: (state, data = []) => {
      state.settleTypeList = data
    }
  },
  plugins: [persistedState({ storage: window.sessionStorage })]
})

export default store
